package com.qk.management.aop.aspect;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.qk.management.aop.anno.Cacheable;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;

/**
 *
 * @author lyl
 * @created 2025/10/18 20:00
 * @description
 *
 */
@Slf4j
@Aspect
@Component
@SuppressWarnings("all")
public class CacheableAspect {
    @Autowired
    private StringRedisTemplate redisClient;

    @Pointcut("@annotation(com.qk.management.aop.anno.Cacheable)")
    public void pt() {}

    @Around("pt()")
    public Object cache(ProceedingJoinPoint pjp) throws Throwable {
        Object returnValue = null;
        String key = null;
        long expireTime = 0L;
        TimeUnit expireTimeUnit = null;
        try {
            Class<?> clazz = pjp.getTarget().getClass();
            String name = pjp.getSignature().getName();
            Method method = clazz.getMethod(name);
            Cacheable annotation = method.getAnnotation(Cacheable.class);
            key = annotation.keyPrefix() + ":" + (annotation.Key().equals("") ? name : annotation.Key());
            expireTime = annotation.expireTime();
            expireTimeUnit = annotation.expireTimeUnit();

            String vlue = redisClient.opsForValue().get(key);
            if (ObjectUtil.isNotEmpty(vlue)){
                return JSONUtil.toBean(vlue,method.getReturnType());
            }
        }catch (Exception e){
            log.error("redis查询异常{}", e.getMessage());
        }
        try {
            returnValue = pjp.proceed();
        }catch (Throwable e){
            log.error("业务失败：{}", e.getMessage());
            throw new Exception(e.getMessage());
        }
        try {
            redisClient.opsForValue().set(key, JSONUtil.toJsonStr(returnValue), expireTime, expireTimeUnit);
        }catch (Exception e){
            log.error("redis保存异常{}", e.getMessage());
        }
        return returnValue;
    }
}
